package com.ljn.controller;

import com.ljn.core.dto.common.User;
import com.ljn.core.dto.common.constant.ConstSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by liujunnan on 2017/11/11.
 */
@Controller
public class BaseController {
    /**
     * 根据key获取session中的对象
     * @param <T>        实体Bean类型
     * @param bean       实体Bean.class
     * @param sessionKey 缓存中存放的key
     * @return 对象
     */
    protected <T> T getFromSession(Class<T> bean, String sessionKey) {
        HttpSession getSession = this.getSession();
        T t = (T) getSession.getAttribute(sessionKey);
        return t;
    }
    /**
     * 获得HttpSession对象
     * @param flag 如果当前session不存在是否重新创建session
     * @return HttpSession
     */
    protected HttpSession getSession(boolean flag) {
        return this.getRequest().getSession(flag);
    }

    /**
     * 一般用于获取HttpSession的方法
     * @return 返回HttpSession对象
     */
    protected HttpSession getSession() {
        return this.getRequest().getSession();
    }

    /**
     * 获取HttpServletRequest对象
     * @return httpServletRequest对象
     */
    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
    /**
     * 用于获取当前登录的用户的详细信息
     */
    protected User getCurrUserFromSession() {
        User user = getFromSession(User.class, ConstSession.LOGIN_USER_SESSION);
        return null == user ? null : user;
    }

    /**
     * 用于获取当前登录的用户的id
     */
    protected String getCurrUserIDFromSession() {
        //获取session中的用户信息
        User user = this.getCurrUserFromSession();
        return null == user ? null : user.getUserId();
    }

}
